<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body{
            height: 3000px;
        }
        a{
            position: fixed;
            right: 0;
            bottom: 0;
        }

        .goback {
            position: fixed;
            right: 0;
            bottom: 0;
            width: 100px;
            height: 50px;
            background-color: #f00;
        }
    </style>
</head>
<body>

    <!-- <a href="#top">返回顶部</a> -->

    <div class="goback"></div>

    <script>

        // 返回顶部 ：  页面被卷去的高度  scrollTop在慢慢减小

        var oDiv = document.querySelector('.goback') ;

        var flag = true ;
        oDiv.onclick = function() {
            if(flag) {
                 // 改变scrollTop的值
                 flag = !flag ;
                var t = setInterval(function() {
                    document.documentElement.scrollTop-=10;
                    // 滚动条所在的位置不一定总是100的倍数
                    if(document.documentElement.scrollTop <= 0) {                       
                        clearInterval(t);
                        flag = !flag ;
                    }
                } , 10)
            }   
        }

    </script>
    
</body>
</html>